package me.sealer.ssm.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.sealer.ssm.mapper.ShortUrlMapper;
import me.sealer.ssm.model.ShortUrl;
import me.sealer.ssm.service.ShortUrlService;
import org.springframework.stereotype.Service;

/**
 * @author sealer
 * @date 2017/07/11
 */
@Service
@Slf4j
public class ShortUrlServiceImpl implements ShortUrlService {
    private final ShortUrlMapper shortUrlMapper;

    public ShortUrlServiceImpl(ShortUrlMapper shortUrlMapper) {
        this.shortUrlMapper = shortUrlMapper;
    }

    @Override
    public ShortUrl selectByLongUrl(String longUrl) {
        return shortUrlMapper.selectByLongUrl(longUrl);
    }

    @Override
    public ShortUrl selectByShortUrl(String shortUrl) {
        return shortUrlMapper.selectByShortUrl(shortUrl);
    }

    @Override
    public void deleteByLongUrl(String longUrl) {
        shortUrlMapper.deleteByLongUrl(longUrl);
    }

    @Override
    public void insertOne(ShortUrl shortUrl) {
        if (shortUrl == null) {
            return;
        }

        //如果该长URL不存在， 则计数器值为1
        if (selectByLongUrl(shortUrl.getLongUrl()) == null) {
            shortUrl.setLongNumber(1);//该地址初次生成短URL
        } else {
            /*//删除所有旧关联
            this.deleteByLongUrl(shortUrl.getLongUrl());
            //生成新关联。
            this.insertOne(shortUrl);*/

            //该地址不是第一次生成短URL， 需要将该长地址的计数器加1
            ShortUrl shortUrlTmp = selectByLongUrl(shortUrl.getLongUrl());
            shortUrl.setLongNumber(shortUrlTmp.getLongNumber() + 1);
        }

        shortUrlMapper.insertOne(shortUrl);
    }

    @Override
    public int selectCountByLongUrl(String longUrl) {
        return shortUrlMapper.selectCountByLongUrl(longUrl);
    }

    @Override
    public void updateByLongUrl(ShortUrl shortUrl) {
        if (shortUrl == null) {
            return;
        }

        String l = shortUrl.getLongUrl();

        /*int count = this.selectCountByLongUrl(l);
        if (count != 1) {
            log.error("错误：该长URL对应的短URL不只一条！");
            return;
        }*/

        ShortUrl shortUrl1 = selectByLongUrl(l);
        if (shortUrl1 == null) {
            log.error("错误：该长URL对应的短URL不存在！");
            return;
        }

        shortUrlMapper.updateByLongUrl(shortUrl);
    }
}
